package biz.master.mgbean;

import biz.master.dto.Product;
import biz.master.dto.ProductCategory;
import biz.master.service.ProductCategorySvr;
import biz.master.service.ProductSvr;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import org.primefaces.component.datatable.DataTable;
import org.primefaces.context.RequestContext;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import javax.servlet.ServletContext;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.io.Serializable;
import java.util.HashMap;
import java.util.List;

@ManagedBean(name = "productMgb")
@ViewScoped
public class ProductMgb implements Serializable {

    /**
     *
     */
    private static final long serialVersionUID = -2658816198129548602L;
    private Integer idSearch;
    private String nameSearch;
    private Integer activeSearch;
    private List<Product> resultSearch;
    private Product selected;
    private DataTable dtResult;
    ProductSvr dao = new ProductSvr();

    public ProductMgb() {
        super();
        this.reset();
    }

    public DataTable getDtResult() {
        return dtResult;
    }

    public void setDtResult(DataTable dtResult) {
        this.dtResult = dtResult;
    }

    public List<ProductCategory> getCategories() {
        ProductCategorySvr d = new ProductCategorySvr();
        return d.search(null);
    }

    public Integer getActiveSearch() {
        return activeSearch;
    }

    public void setActiveSearch(Integer activeSearch) {
        this.activeSearch = activeSearch;
    }

    public List<Product> getResultSearch() {
        return resultSearch;
    }

    public void setResultSearch(List<Product> resultSearch) {
        this.resultSearch = resultSearch;
    }

    public Product getSelected() {
        return selected;
    }

    public void setSelected(Product selected) {
        this.selected = selected;
    }

    public void add() {
        selected = new Product();
    }

    public void reset() {
        idSearch = null;
        nameSearch = null;
        selected = null;
    }

    public Integer getIdSearch() {
        return idSearch;
    }

    public void setIdSearch(Integer idSearch) {
        this.idSearch = idSearch;
    }

    public String getNameSearch() {
        return nameSearch;
    }

    public void setNameSearch(String nameSearch) {
        this.nameSearch = nameSearch;
    }

    public void search() {

        Product o = new Product();
        o.setId(idSearch);
        o.setName(nameSearch);
        resultSearch = dao.search(o);
    }

    public void view(Product value) {
        selected = value;
    }

    public boolean checkDup(String value) {
        Product item = new Product();
        item.setName(value);
        if (dao.search(item).size() == 0)
            return false;
        return true;
    }

    public void save() {
        FacesContext context = FacesContext.getCurrentInstance();

        if (selected.getId() != null)
            dao.update(selected);
        else {
            if (checkDup(selected.getName())) {
                RequestContext.getCurrentInstance().addCallbackParam(
                        "checkBusinessFail", true);
                context.addMessage("growl", new FacesMessage(
                        FacesMessage.SEVERITY_ERROR, "Add Error",
                        "Duplicate Name:" + selected.getName()));
                return;
            }
            dao.create(selected);
        }
        context.addMessage("growl", new FacesMessage("Operation Success",
                "Save ID: " + selected.getId()));
        search();

    }

    public void delete() {

        dao.delete(selected.getId());
        search();
        FacesContext.getCurrentInstance().addMessage(
                "growl",
                new FacesMessage("Operation Success", "Delete ID: "
                        + selected.getId())
        );
    }

    public String exportPDF() {

        HttpServletResponse httpServletResponse = (HttpServletResponse) FacesContext.getCurrentInstance().getExternalContext().getResponse();
        httpServletResponse.addHeader("Content-disposition", "attachment; filename=report.pdf");
        ServletOutputStream servletOutputStream;
        try {
            init();
            servletOutputStream = httpServletResponse.getOutputStream();
            JasperExportManager.exportReportToPdfStream(jasperPrint, servletOutputStream);
        } catch (Exception e) {

            e.printStackTrace();
        }

        FacesContext.getCurrentInstance().responseComplete();
        return null;
    }

    JasperPrint jasperPrint;

    public void init() throws JRException {
        JRBeanCollectionDataSource beanCollectionDataSource = new JRBeanCollectionDataSource(this.resultSearch);
        ServletContext servletContext = (ServletContext) FacesContext
                .getCurrentInstance().getExternalContext().getContext();
        InputStream is = servletContext.getResourceAsStream("/reports/Product.jasper");
        //String  reportPath=  FacesContext.getCurrentInstance().getExternalContext().getRealPath("/reports/Product.jasper");
        jasperPrint = JasperFillManager.fillReport(is, new HashMap(), beanCollectionDataSource);
    }
}
